<?php
namespace app\user\controller;

use \think\Controller;
use think\Request;
use think\Session;
use \think\Cookie;
use think\Hook;
use think\Db;
use app\user\traits\controllers\TraitUser;

/**
 * 会员资料填写
 */
class UserInfo extends \app\common\controller\Api
{
	use \app\user\traits\models\UserInfoCheck;
	use \app\common\traits\controller\TraitUpload;
	use TraitUser;
	//use \app\common\traits\controller\TraitController;
	//前置操作
    protected $beforeActionList = [
        'checkLogin',
    ];
    
    //判断是否登陆
    protected function checkLogin()
    {
        if (!model('Users')->checkLogin()) {
        	Session::set('redirect_url', Request::instance()->url(true));
            $this->redirect('@user/login');
            exit;
        }
    }
    /**
     * [getBindCard 绑定房车]
     * @return [type] [description]
     */
    public function getBindCard()
    {
    	return view('user/bindcard');
    	//记住填写信息
    	// $b = $this->old();
		//    if (empty($b)) {
		//        $b['number']='';
		//        $b['mobile']='';
		//    }
    	//return view('user/bindcard',['b'=>$b]);
    }
    /**
     * [postSendCode 发送手机验证码]
     * @return [type] [description]
     */
    public function getSendCode()
    {
        $phone = input('phone');
        $re = model('PhoneCode')->send($phone);
        return $re;
    }
    /**
     * [postBindCardForm 绑定房车表单]
     * @param string $value [description]
     */
    public function postBindCardForm()
    {
    	//$this->flash();
    	//return $this->getBindCard();
    	$card_num   = input('post.number');
    	$phone_t    = input('post.mobile');
    	$phone_code = input('post.phone_code');
    	$re = model('PhoneCode')->check($phone_code,session_id());
    	if ($re) {
    		$cardinfo =  Db::table('cards')->where('card_num',$card_num)->find();
    		if (!empty($cardinfo)) {
    			if ($phone_t==$cardinfo['user_phone']) {
    				//绑定成功(1)<==>房车有用户id
    				$res = Db::table('caravan')->where('id',$cardinfo['caravan_id'])->setField('user_id', session('user.id'));
	    			if ($res) {
	    				//清除第一次登陆记录
	    				Cookie::delete('firstlogin');
	    				//更新user相应数据
	    				Hook::exec('app\\behavior\\Base','UpdateUserInfo',$cardinfo['caravan_id']);
	    				Hook::exec('app\\behavior\\Base','updatestatus',$card_num);
	    				$this->success('绑定成功','/userinfo/sethotdate');
	    				}else{
	    				$this->success('您已绑定过卡号','/userinfo/sethotdate');	
	    				}
    			}else{
    				$this->error('卡号与手机号不匹配','/userinfo/bindcard');
    			}
    		}else{
    			$this->error('没有该卡号','/userinfo/bindcard');
    		}
    	}else{
    		$this->error('手机验证码错误','/userinfo/bindcard');
    	}
    }
    /**
     * [DateArray 获取日期数组]
     * @param string $value [description]
     */
    public function DateArray($sdate,$edate)
    {
    	$stime=strtotime($sdate);
        $etime=strtotime($edate);
        while($stime <= $etime){
        $datetime[] = date('Y-m-d',$etime);
        $etime=$etime - 3600*24;
        } 
        return $datetime;
    }
    /**
     * [getDateArray 获取热门日期数组]
     * @param string $value [description]id
     */
    public function getDateArray($data)
    {
    	if (is_array($data)) {
    		foreach ($data as $val) {
    			if (is_array($val)) {
    				$date_array = $this->DateArray($val['start_date'],$val['end_date']);
    			}
    		}
    		$date_array = $this->DateArray($data['start_date'],$data['end_date']);
    	}
    	return $date_array;
    }
    /**
     * [getSetHotData 分享热门日期]
     * @return [type] [description]
     */
    public function getSetHotDate()
    {
    	// $a = Db::table('user_caravan_calendar')->where('caravan_id',2)->delete();
    	// halt($a);测试
    	$caravan_user_id = db('caravan')->where('user_id',session('user.id'))->value('id');
    	if (empty($caravan_user_id)) {
    		$this->error('请绑定您的房车','/userinfo/bindcard');
    	}
    	//获取热门日期
    	$camp_id    = Db::table('caravan')->where('user_id',session('user.id'))->value('services');
    	$data       = model('common/Camps')->getPeakDate($camp_id);
    	$date_array = $this->getDateArray($data);
    	$this->assign('data',$data);
    	return view('user/bindcardsetdate',['date_array'=>json_encode($date_array)]);
    }
    /**
     * [postHotDateForm 分享热门日期表单]
     * @return [type] [description]
     */
    public function postHotDateForm()
    {
    	//获取日期
    	$init_dates['sdate'] = input('post.sdate');
    	$init_dates['edate'] = input('post.edate');
    	$user_id = session('user.id');
    	$caravan_user_id = db('caravan')->where('user_id',session('user.id'))->value('id');
    	//$user_id = 2;测试
    	//$caravan_user_id = 2;
    	//房车日历表初始化并分享旺季
    	$re = model("Users")->BindRv($init_dates,$caravan_user_id);
    	if ($re) {
    		return $this->success(lang('绑定成功'),url('/user/index','','','user'));
    	}else{
    		return $this->error(model('Users')->getError());
    	}
    }
	/**
	 * [getPersonInfo 个人信息界面]
	 * @return [type] [description]
	 */
	public function getPersonInfo()
	{
		$sex = model('ContactInfos')->getSex();
		$list = model('Users')->getLoginUserInfo()->toArray();
		$b=1;
		if ($a = $this->old()) {
            $list = array_merge($list,$a);
        }
		return view('user/personinfo',['list'=>$list,'sex'=>$sex,'b'=>$b]);
	}
	/**
	 * [postUpdateInfoForm 个人信息表单]
	 * @return [type] [description]
	 */
	public function postUpdateInfoForm()
	{
		//缓存记录
        $this->flash();
        $post_personal_info['nickname'] = input('post.nickname');
        //判断昵称是否重复
        // if (!input('post.nickname')) {
        // 	$re = model('Users')->where('nickname',input('post.nickname'))->find();
	       //  if (empty($re)) {
	       //      return $this->error(lang('该昵称存在'));
	       //  }
        // }
        //必填项检测
    	$check_info['email'] = input('post.email');
        $check_info['real_name'] = input('post.real_name');
        $re = model('Users')->where('id',session('user.id'))->find();
        if (!empty($re->email)&&!empty($re->real_name)) {
        	//必填项
        	$post_personal_info['email'] = $re->email;
        	$post_personal_info['real_name'] = $re->real_name;
    	}
    	if (!model('Users')->getCheckNull($check_info)) {
        		return $this->error('请完善必填项');
        }
        $post_personal_info['email'] = input('post.email');
        $post_personal_info['real_name'] = input('post.real_name');
		$post_personal_info['sex'] = input('post.sex');
		$post_personal_info['birthday'] = input('post.birthday');
		$post_personal_info['wh_accpet'] = input('post.wh_accpet');
        $post_personal_info['phone'] = input('post.phone');
		$post_personal_info['telephone'] = input('post.telephone');
		$post_personal_info['address'] = input('post.address');
		//增加身份证号
		$post_personal_info['idnumber'] = input('post.idnumber');
        //头像上传
		$x1 =input('post.x1') ;$y1 =input('post.y1') ;$x2 =input('post.x2');$y2 =input('post.y2');
		$b = input('file.image_file');//文件上传判断
		if ($b) {
			$w=$x2-$x1;$h=$y2-$y1;
			$this->setUploadField('image_file')->crop($w,$h,$x1,$y1)->upload();
			$post_personal_info['head'] = $this->getUploadInfos('url');
		}
        $id = session('user.id');
        $res = model('Users')->updatePersonInfo($id,$post_personal_info);
        if ($res) {
        	//绑定房车-行为
        	Hook::exec('app\\behavior\\Base','bindcard',$data = null);
        	return $this->success(lang('完善个人信息成功'),url('/userinfo/personinfo','','','user'));
        }else{
        	return $this->error(lang('更新信息失败'));
        }
	}
	/**
	 * [getCheckEmail 检测邮箱格式]
	 * @return [type] [description]
	 */
	public function getCheckEmail()
	{
		$email = input('email');
		$re = $this->cheack(['email'=>$email]);
		if ($re) {
			return 1;
		}else{
			return json(0);
		}
	}
	/**
	 * [getCheckNickName 检测昵称]
	 * @return [type] [0为昵称不存在]
	 */
	public function getCheckNickName()
	{
		$nickname = input('nickname');
		$re = model('Users')->where('nickname',$nickname)->find();
		if (empty($re)) {
            return json(0);
        }
        return 1;
	}
	/**
	 * [getUpdatePassWord 修改密码界面]
	 * @return [type] [description]
	 */
	public function getupdatePassWord()
	{
		return view('user/changepwd');
	}
	/**
	 * [getCheckOldPsd 判断原密码是否正确]
	 * @return [type] [description]
	 */
	public function getCheckOldPsd()
	{
		$old_psd = input('old_psd');
		$now_psd = model('Users')->getLoginUserInfo('password');
		if ($now_psd<>md5($old_psd)) {
			return json(0);
		}
		return 1;
	}
	/**
	 * [postUpdatePasswordForm 修改密码表单]
	 * @return [type] [description]
	 */
	public function postUpdatePasswordForm()
	{
		$old_psd = input('post.old_psd');
		$now_psd = model('Users')->getLoginUserInfo('password');
		if ($now_psd<>md5($old_psd)) {
			return $this->error(lang('原密码错误'));
		}
		$password = input('post.password');
		$repassword = input('post.repassword');
		$re = $this->cheack(['password'=>$password,'repassword'=>$repassword]);
		$mobile = model('Users')->getLoginUserInfo('mobile');
		if ($re) {
			$result=model("Users")->where('mobile',$mobile)->setField('password',md5($password));
			if (!$result) {
				return $this->error(lang('密码修改失败'));
			}
			return $this->success(lang('密码修改成功'),'/user/index');
		}else{
			return $this->error(lang('密码不一致'));
		}
	}
	/////////////////////注册审核信息////////////
	/**
	 * [getContactsInfo 注册审核列表]
	 * @return [type] [description]
	 */
	public function getMemCheck()
	{
		return view('user/memcheck');
	}
	public function postMemCheckForm()
	{
		
	}
	public function getCaravantCheck()
	{
		return view('user/caravantcheck');
	}
	public function postCaravanCheckForm()
	{
		
	}
	//////////////////////////////////实名认证//////////////////////////////
	public function getIdentityInfo()
	{
		//审核通过
		$rz = model('Users')->getLoginUserInfo('authentication');
		if ($rz) {
			$this->redirect('/userinfo/rzok');
            exit;
		}
		$this->CheckIdentityInfo();
		return view('user/realnameapprove');
	}
	/**
	 * [postIdentityInfoForm 实名认证表单]
	 * @return [type] [description]
	 */
	public function postIdentityInfoForm()
	{
		//营地id
		$post_personal_info['camp_id'] = model('Users')->getLoginUserInfo('camp_id');
		//账号
		$post_personal_info['account'] = model('Users')->getLoginUserInfo('mobile');
		$post_personal_info['user_id'] = session('user.id');
		$post_personal_info['name'] = input('post.name');
		$post_personal_info['card_id'] = input('post.card_id');
		//验证身份证号格式
		$re  = model('Authentication')->isCreditNo($post_personal_info['card_id']);
		if (!$re) {
			return $this->error('身份证号格式错误');
		}
		//身份证正面
		$this->setUploadField('card_pic_z')->upload();
		$post_personal_info['card_pic_z'] = $this->getUploadInfos('url');
		//身份证反面
		$this->setUploadField('card_pic_f')->upload();
		$post_personal_info['card_pic_f'] = $this->getUploadInfos('url');
		// //行驶证照片
		// $this->setUploadField('license')->upload();
		// $post_personal_info['license'] = $this->getUploadInfos('url');
		// //人车照片
		// $this->setUploadField('user_car_pic')->upload();
		// $post_personal_info['user_car_pic'] = $this->getUploadInfos('url');
		$post_personal_info['created_at'] = date('Y-m-d H:i:s');
		$res = db('user_certification')->insert($post_personal_info);
        if ($res) {
        	return $this->success(lang('提交成功'),'/userinfo/waitidentityinfo');
        }else{
        	return $this->error(lang('提交失败'));
        }
	}
	/**
	 * [getWaitIdentityInfo 等待实名认证审核界面]
	 * @param string $value [description]
	 */
	public function getWaitIdentityInfo()
	{
		$user_id = session('user.id');
		$info = db('user_certification')->where('user_id',$user_id)->find();
		return view('user/waitrenzh',['info'=>$info]);
	}
	/**
	 * [getRZok 实名认证成功界面]
	 * @param string $value [description]
	 */
	public function getRZok()
	{
		$user_id = session('user.id');
		$info = db('user_certification')->where('user_id',$user_id)->find();
		return view('user/rzok',['info'=>$info]);
	}
	public function CheckIdentityInfo()
	{
		$re = Db::table('user_certification')->where('user_id',session('user.id'))->find();
		if (!empty($re)) {
			$this->redirect('@userinfo/waitidentityinfo');
            exit;
		}
	}
	public function getAgainSubmit()
	{
		return view('user/realnameapprove');
	}
	public function getCheckIdentity()
	{
		$id_num = input('card_id');
		$re  = model('Authentication')->isCreditNo($id_num);
		if (!$re) {
			return json(0);
		}
		return 1;
	}
}
